(function(){

    $.fn.multiselect = function (options) {
        var opts = {
            filter: null
        };
        $.extend(opts, options);

        $(this).on("click", ".selected-group", function (e) {
            if (!$(e.target).hasClass("list-selected") && $(e.target).closest(".list-selected").length > 0) {
                $(e.target).closest("li").remove();
                e.stopPropagation();
            }
        });
        $(this).on("click", ".dropdown-menu>li", function (e) {
            var $this = $(this);
            var $item = $this.find("a");

            if (typeof (opts.filter) == "function") {
                var result = opts.filter.call($this[0], $item.data("value"), $item.text(), getSelected());
                if (result === false){
                    return;
                }
            }

            $this.closest(".multiselect")
                 .find(".list-selected")
                 .append($this.clone());
        });

        function getSelected(){
            var selected = [];
            $(".selected-group .list-selected > li > a").each(function(){
                var $this = $(this);
                selected.push({ value: $this.data("value"), text: $this.text() });
            });
            return selected;
        }
    }

})();